package com.foruo.demo.jdbc.dao;

import com.foruo.demo.jdbc.datasource.ThreadLocalPool;
import com.foruo.demo.jdbc.entity.SimpleEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.TimeUnit;

/**
 * 模拟dao层
 * @author GaoYuan
 */
@Component
public class SimpleDao {

    @Autowired
    ThreadLocalPool threadLocalPool;

    public SimpleEntity get() throws Exception{
        Connection connection = threadLocalPool.getConnection();
        System.out.println("   dao层获取的连接 " + connection.hashCode());
        PreparedStatement ps = connection.prepareStatement("select username from sys_user where id = 1");
        ResultSet rs = ps.executeQuery();

        SimpleEntity simpleEntity = new SimpleEntity();
        while (rs.next()) {
            String username = rs.getString(1);
            simpleEntity.setUsername(username);
        }

        try {
            // 为了测试
            TimeUnit.SECONDS.sleep(2);
        }catch (Exception e){

        }

        if(rs!=null){
            try{rs.close();}catch (Exception e){}
        }
        if(ps!=null){
            try{ps.close();}catch (Exception e){}
        }
        return simpleEntity;
    }

}
